package com.hykj.xxltest.contral;

import com.alibaba.fastjson.JSON;
import com.hykj.xxltest.auto.SysGeneratorService;
import com.hykj.xxltest.base.AppBack;
import com.hykj.xxltest.config.AlipayConfig;
import com.hykj.xxltest.model.AdminModel;
import com.hykj.xxltest.service.AdminService;
import com.hykj.xxltest.service.PayOrderService;
import com.hykj.xxltest.utils.AlipaySignature;
import com.hykj.xxltest.utils.WechatpayNotifyVerifyUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@ApiIgnore
public class BaseController {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    AdminService adminService;


    @Autowired
    SysGeneratorService sysGeneratorService;

    @Autowired
    PayOrderService payOrderService;




    @RequestMapping("/auto")//自动生成代码
    @ResponseBody
    @ApiOperation(
            value = "",
            httpMethod = "POST")
    public void auto(HttpServletRequest request, HttpServletResponse response,
                     String tablename) throws IOException {


        String[] tables;
        if (StringUtils.isEmpty(tablename)) {
            List<Map<String, Object>> tempList = sysGeneratorService.queryList(new HashMap<>());
            String[] tables2 = new String[tempList.size()];
            for (int i = 0; i < tempList.size(); i++) {
                tables2[i] = tempList.get(i).get("tableName").toString();
            }
            tables = tables2;
        } else {
            String[] tables2 = tablename.split(",");
            tables = tables2;
        }


        byte[] data = sysGeneratorService.generatorCode(tables);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"autoCode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }


    @RequestMapping("/admin/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/index.html");
        return;
    }


    @RequestMapping("/loginAdmin")
    @ResponseBody
    @ApiOperation(
            value = "后台登录",
            httpMethod = "POST")
    public AppBack loginAdmin(@RequestParam String username,
                              @RequestParam String password,
                              HttpServletRequest request) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        Map condition = new HashMap();
        condition.put("username", username);
        condition.put("password", password);
        List<AdminModel> list = adminService.getDList(condition);
        if (list.size() == 0) {
            return new AppBack(-1, "用户名或密码错误");
        }
        if (list.get(0).getStatus() != 0) {
            return new AppBack(-1, "账号被冻结");
        }
        request.getSession().invalidate();
        request.getSession().setAttribute("admin", list.get(0));
        request.getSession().setAttribute("role", 1);
        return new AppBack(0, "登录成功");
    }



    @RequestMapping("/getSession")
    @ResponseBody
    @ApiOperation(
            value = "获得登录状态",
            httpMethod = "POST")
    public AppBack loginStaff(@SessionAttribute(required = false) Integer role,
                              @SessionAttribute(required = false) AdminModel admin) {
        logger.info( "role "+role);
        if (role == null) {
            return new AppBack(-1, "登录失效");
        }
        AppBack appBack = new AppBack();
        appBack.add("role", role);
        appBack.add("admin", admin);
        return appBack;
    }


    /**
     * －－－－－－－－－微信支付回调－－－－－－－－－
     */
    @RequestMapping("/wechatNotify")//继续支付订单
    @ResponseBody
    public String wechatNotify(HttpServletRequest request) throws Exception {

        logger.info("wechatNotify");

        String weixinReqXml = getRequestData(request);
        if (!StringUtils.isEmpty(weixinReqXml)) {
            Map<String, String> wxMap = WechatpayNotifyVerifyUtil.parseXmlToMap(weixinReqXml);

            logger.info(wxMap.toString());
            String return_code = wxMap.get("return_code");

            if ("SUCCESS".equals(return_code)) {
                String result_code = wxMap.get("result_code");
                String out_trade_no = wxMap.get("out_trade_no");// 体验店系统的订单号，与请求一致
                String transaction_id = wxMap.get("transaction_id");// 微信交易号
                logger.info(result_code + "__result_code");
                float total_fee = Float.parseFloat(wxMap.get("total_fee")) / 100;// 订单总金额，单位为分
                if ("SUCCESS".equals(result_code)) {

                    if (WechatpayNotifyVerifyUtil.verifySign(wxMap)) {

                        // 支付成功
                        notifySuccess(out_trade_no);


                    } else {
                        logger.error("WeixinpayService.payNotify sign verify error!");
                        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>";
                    }
                } else {
                    // 支付失败
                    logger.info("支付失败");
                    String err_code = wxMap.get("err_code");
                    if ("ORDERCLOSED".equals(err_code)) {

                    } else {

                    }
                }
            } else {
                String return_msg = wxMap.get("return_msg");
                logger.error("WeixinpayService.payNotify error!" + return_msg);
            }
        }

        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    /**
     * －－－－－－－－－支付宝支付回调－－－－－－－－－
     */
    @RequestMapping("/aliPayNotify")//继续支付订单
    @ResponseBody
    public String aliPayNotify(HttpServletRequest request,
                               @RequestParam(defaultValue = "") String out_trade_no,
                               @RequestParam(defaultValue = "") String trade_no,
                               @RequestParam(defaultValue = "") String total_amount,
                               @RequestParam(defaultValue = "") String trade_status) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //体验店订单号
        logger.info("获得支付宝回调参数" + JSON.toJSONString(params));

        if (!"TRADE_SUCCESS".equals(trade_status)) { //支付不成功

            return "success";
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.input_charset, "RSA2");

        logger.info("verify_result " + verify_result);
        if (verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上体验店的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            notifySuccess(out_trade_no);
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            return "success";

            //////////////////////////////////////////////////////////////////////////////////////////
        } else {//验证失败
            return "fail";
        }
    }

    private void notifySuccess(String  code){

        if (code.startsWith("PO")) {
            payOrderService.payOrderSuccess(code);
        }

    }

    private String getRequestData(HttpServletRequest request) throws Exception {
        String charset = getCharset(request);
        StringBuffer buffer = new StringBuffer();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));
            String tempLine = null;
            while ((tempLine = rd.readLine()) != null) {
                buffer.append(tempLine);
            }
        } finally {
            try {
                if (rd != null) {
                    rd.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString().trim();
    }

    private String getCharset(HttpServletRequest request) {
        if (request != null) {
            return request.getCharacterEncoding();
        }
        return "UTF-8";
    }



}
